package ink.tiptop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ink.tiptop.persist.domain.entity.ZjfUserModuleVersionEntity;
import ink.tiptop.dto.req.version.AddZjfUserModuleVersionRequest;
import ink.tiptop.dto.req.version.DeleteZjfUserModuleVersionRequest;
import ink.tiptop.dto.req.version.QueryZjfUserModuleVersionRequest;
import ink.tiptop.dto.req.version.UpdateZjfUserModuleVersionRequest;
import ink.tiptop.enums.EResp;
import ink.tiptop.common.domain.WebworkResponse;
import ink.tiptop.dto.resp.version.ZjfUserModuleVersionInfo;
import ink.tiptop.common.cache.CacheAble;
import ink.tiptop.common.cache.CacheEvict;
import ink.tiptop.common.cache.ECaches;
import ink.tiptop.common.cache.ICache;
import ink.tiptop.exception.JDTException;
import ink.tiptop.exception.JDTExceptionMsg;
import ink.tiptop.persist.dao.ZjfUserModuleVersionMapper;
import ink.tiptop.common.domain.req.PageRequest;
import ink.tiptop.common.domain.rsp.Response;
import ink.tiptop.service.AbstractBaseService;
import ink.tiptop.service.CacheSearch;
import ink.tiptop.service.ZjfUserModuleVersionService;
import ink.tiptop.utils.ParamUtils;
import ink.tiptop.utils.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用于用户-模块版本的映射
 * User:module = 1:n
 * (ZjfUserModuleVersionEntity)表服务实现类
 *
 * @author makejava
 * @since 2020-06-21 20:39:19
 */
@Service("zjfUserModuleVersionService")
@Slf4j
public class ZjfUserModuleVersionServiceImpl extends AbstractBaseService<ZjfUserModuleVersionEntity> implements ZjfUserModuleVersionService {
    private static final String CACHE_KEY = "MODULE_VERSION";
    private static final String CACHE_CLEAR = CACHE_KEY + "*";
    @Resource
    private ZjfUserModuleVersionMapper zjfUserModuleVersionMapper;
    @Autowired
    private CacheSearch<ZjfUserModuleVersionEntity> cacheSearch;
    @Autowired
    private ICache<String> cache;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ZjfUserModuleVersionEntity queryById(Integer id) {
        return this.zjfUserModuleVersionMapper.selectById(id);
    }

    /**
     * 查询多条数据
     *
     * @return 对象列表
     */
    @Override
    public List<ZjfUserModuleVersionEntity> queryByUser(String user) {
        String cacheKey = CACHE_KEY + "ALL" + user;
        List<ZjfUserModuleVersionEntity> list = cacheSearch.getList(cacheKey, ZjfUserModuleVersionEntity.class, ECaches.DAY);
        if (list == null) {
            ZjfUserModuleVersionEntity zjfUserModuleVersionEntity = new ZjfUserModuleVersionEntity();
            zjfUserModuleVersionEntity.setUser(user);
            list = this.zjfUserModuleVersionMapper.selectList(new QueryWrapper<>(zjfUserModuleVersionEntity));
            cache.setVal(cacheKey, JSON.toJSONString(list), ECaches.DAY);
        }
        return list;
    }

    /**
     * 新增数据
     *
     * @param zjfUserModuleVersionEntity 实例对象
     * @return 实例对象
     */
    @Override
    @CacheEvict(key = CACHE_CLEAR, type = ECaches.DAY)
    public ZjfUserModuleVersionEntity insert(ZjfUserModuleVersionEntity zjfUserModuleVersionEntity) {
        this.zjfUserModuleVersionMapper.insert(zjfUserModuleVersionEntity);
        return zjfUserModuleVersionEntity;
    }

    /**
     * 修改数据
     *
     * @return 实例对象
     */
    @Override
    @CacheEvict(key = CACHE_CLEAR, type = ECaches.DAY)
    public Response update(UpdateZjfUserModuleVersionRequest request) {
        ZjfUserModuleVersionEntity zjfUserModuleVersionEntity = new ZjfUserModuleVersionEntity();
        zjfUserModuleVersionEntity.setId(request.getId());
        int count = zjfUserModuleVersionMapper.selectCount(new QueryWrapper<>(zjfUserModuleVersionEntity));
        if (count == 0) {
            return WebworkResponse.failed(EResp.EVersion.ERROR_EXIST_NOT);
        }
        BeanUtils.copyProperties(request, zjfUserModuleVersionEntity);
        int update;
        try {
            update = this.zjfUserModuleVersionMapper.updateById(zjfUserModuleVersionEntity);
        } catch (DuplicateKeyException e) {
            return WebworkResponse.failed(EResp.EVersion.ERROR_EXIST);
        }
        if (update > 0) {
            return WebworkResponse.SUCCEED;
        }
        return WebworkResponse.failed(EResp.EVersion.ERROR_UPDATE);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    @CacheEvict(key = CACHE_CLEAR, type = ECaches.DAY)
    public boolean deleteById(Integer id) {
        return this.zjfUserModuleVersionMapper.deleteById(id) > 0;
    }

    @Override
    @CacheEvict(key = CACHE_CLEAR, type = ECaches.DAY)
    public Response add(AddZjfUserModuleVersionRequest request) {

        ZjfUserModuleVersionEntity entity = new ZjfUserModuleVersionEntity();
        entity.setUser(request.getUser());
        entity.setVersion(request.getVersion());
        int count = zjfUserModuleVersionMapper.selectCount(new QueryWrapper<>(entity));
        if (count > 0) {
            return WebworkResponse.failed(EResp.EVersion.ERROR_EXIST);
        }
        entity.setDesc(request.getDesc());
        int insert = zjfUserModuleVersionMapper.insert(entity);
        return insert > 0 ? WebworkResponse.SUCCEED : WebworkResponse.ERROR;
    }

    @Override
    @CacheAble(desc = "用户版本缓存注解", keyPrefix = CACHE_KEY, type = ECaches.DAY)
    public Response list(QueryZjfUserModuleVersionRequest request) {
        return super.list(request);
    }

    @Override
    @CacheEvict(key = CACHE_CLEAR, type = ECaches.DAY)
    public Response deleteAll(DeleteZjfUserModuleVersionRequest request) {

        // 1.转换成id类型
        List<Integer> reqIdList = ParamUtils.toIntList(request.getId());
        List<Integer> relatedIdList = getRelatedList(request.getId());

        if (relatedIdList != null && !relatedIdList.isEmpty()) {
            // 请求删除的id列表 删除 关联的id列表 , 剩下的是可以都删除的
            List<Integer> delIdList = reqIdList.stream().filter(req -> !relatedIdList.contains(req)).collect(Collectors.toList());
            if (delIdList == null || delIdList.isEmpty()) {
                return WebworkResponse.failed(EResp.EVersion.ERROR_DELETE_FORBID);
            }
            int rows = zjfUserModuleVersionMapper.deleteBatchIds(delIdList);
            if (rows > 0) {
                return WebworkResponse.failed(EResp.EVersion.ERROR_DELETE_PART);
            }
        } else {

            int count = zjfUserModuleVersionMapper.deleteBatchIds(reqIdList);
            if (count > 0) {
                return WebworkResponse.SUCCEED;
            }
        }
        return WebworkResponse.ERROR;
    }

    private List<Integer> getRelatedList(List<String> reqIdList) {
        String ids = String.join(",", reqIdList);
        // 2.查询到关联的id列表
        return zjfUserModuleVersionMapper.listRelatedIdList(ids);
    }

    @Override
    public void checkVersionExist(String user, String version) {
        ZjfUserModuleVersionEntity entity = new ZjfUserModuleVersionEntity();
        entity.setUser(user);
        entity.setVersion(version);
        if (zjfUserModuleVersionMapper.selectCount(new QueryWrapper<>(entity)) == 0) {
            JDTException.throwException(JDTExceptionMsg.getError(EResp.EVersion.ERROR_EXIST_NOT));
        }
    }

    @Override
    protected void setOrderBy(PageRequest request) {

    }

    @Override
    protected ZjfUserModuleVersionEntity getQueryParam(PageRequest request) {
        ZjfUserModuleVersionEntity entity = new ZjfUserModuleVersionEntity();
        BeanUtils.copyProperties(request, entity);
        return entity;
    }

    @Override
    public Page<ZjfUserModuleVersionEntity> getQueryEntityList(Page<ZjfUserModuleVersionEntity> page, ZjfUserModuleVersionEntity param) {
        return zjfUserModuleVersionMapper.selectPage(page,new QueryWrapper<>(param));
    }

    @Override
    protected Object getResponseList(List<ZjfUserModuleVersionEntity> entityList) {
        List<ZjfUserModuleVersionInfo> infos = new ArrayList<>();
        ZjfUserModuleVersionInfo info;
        for (ZjfUserModuleVersionEntity entity : entityList) {
            info = new ZjfUserModuleVersionInfo();
            BeanUtils.copyProperties(entity, info);
            infos.add(info);
        }
        return infos;
    }
}